/*
 * @Author: diana
 * @Date: 2023-05-05 21:52:34
 * @LastEditTime: 2023-05-06 19:50:35
 */
import React, { useEffect, useState } from "react";
import { ethers } from "ethers";

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import abi from "./CoffeeSeller.json";
import { Badge, Box, Button, ButtonGroup, Divider, Grid, GridItem, Heading, Image, Input, Stack,Text, Textarea } from "@chakra-ui/react";
import {
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react'
declare let window: any;
function App() {
  // 合约地址abi
  const contractAddress = "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9";
  //合约编译的json文件
  const contractABI = abi.abi;
  const toatTime = 2
  // 接收参数
  const [currentAccount, setCurrentAccount] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");

  const [allCoffee, setAllCoffee] = useState([]);

  // 检查是否连接钱包
  const checkIfWalletIsConnected = async () => {
    try {
      //window.ethereum
      const { ethereum } = window;
      // 获取当前网页连接的账户
      const accounts = await ethereum.request({ method: "eth_accounts" });

      if (accounts.length !== 0) {
        const currentAc = accounts[0];
        setCurrentAccount(currentAc);

        toast.success("Wallet is Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      } else {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  // 连接钱包
  const connectWallet = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
        return;
      }
      // 申请连接，弹窗
      const account = ethereum.request({ method: "eth_requestAccounts" });
      setCurrentAccount(account[0]);
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

 

  // 获取已购买的数组以便展示
  const getAllCoffee = async () => {
    try {
      const { ethereum } = window;
      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const coffeeContract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
        console.log("获取咖啡");
        const coffees = await coffeeContract.getCoffees();

        const finalCoffees = coffees.map((item) => {
          return {
            address: item.giver,
            name: item.name,
            message: item.message,
            timestamp: new Date(item.timestamp * 1000),
          };
        });
        console.log(finalCoffees);
        setAllCoffee(finalCoffees);

        console.log("------------#---------------", finalCoffees);
      } else {
        console.log("Ethereum object doesn't exist!");
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    let coffeeContract;
    checkIfWalletIsConnected();

    getAllCoffee();

    // 监听时调用的函数
    const onNewCoffee = (from, name, message, timestamp) => {
      setAllCoffee((pre) => [
        ...pre,
        {
          address: from,
          name: name,
          message: message,
          timestamp: new Date(timestamp * 1000),
        },
      ]);
    };

    if (window.ethereum) {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();

      coffeeContract = new ethers.Contract(
        contractAddress,
        contractABI,
        signer
      );
      coffeeContract.on("NewCoffee", onNewCoffee);
    }

    return () => {
      // 关闭订阅的监听
      if (coffeeContract) {
        coffeeContract.off("NewCoffee", onNewCoffee);
      }
    };
  }, []);

  // 输入框值变化事件
  const handleOnMessageChange = (e) => {
    const { value } = e.target;
    setMessage(value);
  };
  const handleOnNameChange = (e) => {
    const { value } = e.target;
    setName(value);
  };
  const property = {
    imageUrl: 'https://cn.bing.com/images/search?view=detailV2&ccid=GyL5Y1dF&id=5DAE217DFC5A11C794A87C394A743B8213D6A84B&thid=OIP.GyL5Y1dFW96CGltb8UjDkgHaJN&mediaurl=https%3a%2f%2fimg.zcool.cn%2fcommunity%2f01445a5acae323a801204029cf4ead.jpg%401280w_1l_2o_100sh.jpg',
    imageAlt: 'Rear view of modern home with pool',
    beds: 3,
    baths: 2,
    title: 'Modern home in city center in the heart of historic Los Angeles',
    formattedPrice: '$1,900.00',
    reviewCount: 34,
    rating: 4,
  }
  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-1 bg-gray-100">
      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
       

      
         <Heading>Coffees</Heading>
       
     

      
  <Accordion>
  <Box display="flex" flexWrap="wrap">
    <Box width={{ base: '44%', md: '50%' }} p={4}>
    <Badge borderRadius='full' px='2' colorScheme='teal'>
            New
          </Badge>
          <Image src={property.imageUrl} alt={property.imageAlt} />
          <Box
          
            color='gray.500'
            fontWeight='semibold'
            letterSpacing='wide'
            fontSize='xs'
            textTransform='uppercase'
            ml='2'
          >
            {property.beds} beds &bull; {property.baths} baths
          </Box>
          <Box
          mt="1"
          fontWeight="semibold"
          as="h4"
          lineHeight="tight"
          isTruncated
        >
          {property.title}
        </Box>

        <Box>
          {property.formattedPrice}
          <Box as="span" color="gray.600" fontSize="sm">
            / wk
          </Box>
        </Box>
    </Box>
    <Box width={{ base: '44%', md: '50%' }} p={4}>
      {/* Content for second box */}22
    </Box>

    <Box width={{ base: '44%', md: '50%' }} p={4}>
      {/* Content for second box */}33
    </Box>

    <Box width={{ base: '44%', md: '50%' }} p={4}>
      {/* Content for second box */}44
    </Box>
    {/* Continue adding more pairs of Box components for additional rows */}
  </Box>

 

  


        {allCoffee.map((coffee, index) => {
          return (
           
          
            <AccordionItem>
              <h2>
                <AccordionButton>
                  <Box as="span" flex='1' textAlign='left'>
                  {coffee.name}
                  </Box>
                  <AccordionIcon />
                </AccordionButton>
              </h2>
              <AccordionPanel pb={4}>
               <Text>coffeeName: {coffee.name}</Text>
               <Text>Message: {coffee.message}</Text>
              </AccordionPanel>
            </AccordionItem>

           
          );
        })}
 </Accordion>
        <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
        />
      </main>
    </div>
  );
}

export default App;
